#!/bin/bash

# 启动分布式集群示例脚本

set -e

echo "Building cluster-node-manager..."
cargo build --release --example distributed

echo "Starting 3-node distributed cluster..."

# 启动节点 1 (Leader)
echo "Starting node 1 (leader)..."
cargo run --release --example distributed 1 &
NODE1_PID=$!

# 等待节点 1 启动
sleep 3

# 启动节点 2
echo "Starting node 2..."
cargo run --release --example distributed 2 &
NODE2_PID=$!

# 启动节点 3
echo "Starting node 3..."
cargo run --release --example distributed 3 &
NODE3_PID=$!

# 等待集群启动
sleep 5

echo "Cluster started successfully!"
echo "Node 1 API: http://127.0.0.1:8081"
echo "Node 2 API: http://127.0.0.1:8082"
echo "Node 3 API: http://127.0.0.1:8083"
echo "Metrics: http://127.0.0.1:9090/metrics"
echo ""
echo "Press Ctrl+C to stop all nodes"

# 创建清理函数
cleanup() {
    echo "Stopping cluster nodes..."
    kill $NODE1_PID $NODE2_PID $NODE3_PID 2>/dev/null || true
    wait
    echo "All nodes stopped."
}

# 设置信号处理
trap cleanup SIGINT SIGTERM

# 等待直到收到信号
wait
